<template>
  <view class="container">
    <!-- 渐变背景层 -->
    <view class="bg-gradient"></view>
    
    <view class="profile-wrapper">
      <!-- 用户信息卡片 -->
      <view class="profile-card glassmorphism">
        <!-- 头像装饰环 -->
        <view class="avatar-ring" @click="showAvatarOptions">
          <image 
            class="avatar" 
            :src="user.avatar || '/static/default-avatar.png'" 
            mode="aspectFill"
          />
        </view>
        
        <!-- 用户信息 -->
        <view class="info-grid">
          <view class="info-item">
            <uni-icons type="contact" size="20" color="#4A90E2" />
            <text class="info-label">姓名：{{ user.name || '未设置' }}</text>
          </view>
          <view class="info-item">
            <uni-icons type="paperclip" size="20" color="#4A90E2" />
            <text class="info-label">学号：{{ user.student_id || '未设置' }}</text>
          </view>
          <view class="info-item">
            <uni-icons type="star" size="20" color="#4A90E2" />
            <text class="info-label">积分：{{ user.points || 0 }}</text>
          </view>
          <view class="info-item">
            <uni-icons type="list" size="20" color="#4A90E2" />
            <text class="info-label">专业：{{ user.major || '未设置' }}</text>
          </view>
          <view class="info-item">
            <uni-icons type="home" size="20" color="#4A90E2" />
            <text class="info-label">班级：{{ user.class_id || '未设置' }}</text>
          </view>
        </view>
      </view>

      <!-- 数据统计卡片 -->
      <view class="stats-card glassmorphism">
        <view class="stat-item">
          <text class="stat-value">{{ registrationDays }}</text>
          <text class="stat-label">注册天数</text>
        </view>
        <view class="divider"></view>
        <view class="stat-item">
          <text class="stat-value">{{ totalQuestions }}</text>
          <text class="stat-label">答题数</text>
        </view>
        <view class="divider"></view>
        <view class="stat-item">
          <text class="stat-value">{{ correctRate }}%</text>
          <text class="stat-label">答题正确率</text>
        </view>
      </view>

      <!-- 操作按钮 -->
      <view class="action-buttons">
        <button class="logout-button gradient-bg" @click="logout">
          <uni-icons type="logout" size="24" color="#FFF" />
          <text>退出登录</text>
        </button>
      </view>
    </view>

    <!-- 加载动画 -->
    <view v-if="loading" class="loading">
      <view class="spinner"></view>
      <text>加载中...</text>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      user: {},
      registrationDays: 0,
      totalQuestions: 0,
      correctRate: 0,
      loading: false
    };
  },
  onLoad() {
    this.loadUserData();
  },
  onShow() {
    this.getUserPoints();
  },
  methods: {
    async loadUserData() {
      this.user = uni.getStorageSync('user') || {};
      if (!this.user.id) {
        uni.showToast({ title: '请先登录', icon: 'none' });
        try {
          await uni.reLaunch({
            url: '/pages/student/login',
            fail(err) {
              console.error('导航到登录页面失败:', err);
              uni.showToast({ title: '跳转登录失败，请稍后重试', icon: 'none' });
            }
          });
        } catch (err) {
          console.error('导航异常:', err);
          uni.showToast({ title: '导航异常，请检查网络', icon: 'none' });
        }
      }
    },
    async getUserPoints() {
      this.loading = true;
      try {
        const res = await uniCloud.callFunction({
          name: 'getUserPoints',
          data: { user_id: this.user.id }
        });
        if (res.result.code === 0) {
          const data = res.result.data;
          this.user.points = data.points || 0;
          this.registrationDays = data.registrationDays || 0;
          this.totalQuestions = data.totalQuestions || 0;
          // 修复正确率：将整数 4375 转换为 43.75
          this.correctRate = data.correctRate
          uni.setStorageSync('user', this.user);
        } else {
          uni.showToast({ title: res.result.msg || '加载数据失败', icon: 'none' });
        }
      } catch (e) {
        console.error('获取用户数据失败:', e);
        uni.showToast({ title: '加载数据失败', icon: 'none' });
      } finally {
        this.loading = false;
      }
    },
    showAvatarOptions() {
      uni.showActionSheet({
        itemList: ['上传头像', '取消'],
        success: (res) => {
          if (res.tapIndex === 0) {
            this.uploadAvatar();
          }
        },
        fail: (err) => {
          console.error('动作面板失败:', err);
        }
      });
    },
    async uploadAvatar() {
      try {
        // 选择图片
        const { tempFiles } = await uni.chooseImage({
          count: 1,
          sizeType: ['compressed'],
          sourceType: ['album', 'camera']
        });
        if (!tempFiles || tempFiles.length === 0) {
          uni.showToast({ title: '未选择图片', icon: 'none' });
          return;
        }

        this.loading = true;
        // 上传到 UniCloud
        const filePath = tempFiles[0].path;
        const cloudPath = `avatars/${this.user.id}_${Date.now()}.jpg`;
        const uploadRes = await uniCloud.uploadFile({
          filePath,
          cloudPath
        });

        if (!uploadRes.fileID) {
          throw new Error('上传失败');
        }

        // 更新用户头像
        const updateRes = await uniCloud.callFunction({
          name: 'updateUserAvatar',
          data: {
            user_id: this.user.id,
            avatar: uploadRes.fileID
          }
        });

        if (updateRes.result.code === 0) {
          this.user.avatar = uploadRes.fileID;
          uni.setStorageSync('user', this.user);
          uni.showToast({ title: '头像更新成功', icon: 'success' });
        } else {
          throw new Error(updateRes.result.msg || '更新头像失败');
        }
      } catch (e) {
        console.error('头像上传失败:', e);
        uni.showToast({ title: '头像上传失败，请稍后重试', icon: 'none' });
      } finally {
        this.loading = false;
      }
    },
    logout() {
      uni.showModal({
        title: '确认退出',
        content: '确定要退出登录吗？',
        success: async (res) => {
          if (res.confirm) {
            uni.removeStorageSync('user');
            try {
              await uni.reLaunch({
                url: '/pages/student/login',
                fail(err) {
                  console.error('退出登录导航失败:', err);
                  uni.showToast({ title: '跳转登录失败，请稍后重试', icon: 'none' });
                }
              });
            } catch (err) {
              console.error('导航异常:', err);
              uni.showToast({ title: '导航异常，请检查网络', icon: 'none' });
            }
          }
        }
      });
    }
  }
};
</script>

<style scoped>
/* 基础样式 */
.container {
  position: relative;
  min-height: 100vh;
  padding: 24px;
  background: #f8f9fa;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding-bottom: env(safe-area-inset-bottom);
}

.bg-gradient {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  height: 40vh;
  background: linear-gradient(135deg, #4a90e2 0%, #5aa1ff 100%);
  z-index: 0;
  border-radius: 0 0 30% 30%;
}

/* 玻璃拟态效果 */
.glassmorphism {
  background: rgba(255, 255, 255, 0.85);
  backdrop-filter: blur(12px);
  border: 1px solid rgba(255, 255, 255, 0.2);
  box-shadow: 0 8px 32px rgba(31, 38, 135, 0.15);
  border-radius: 24px;
  transition: transform 0.3s ease;
}

.glassmorphism:hover {
  transform: scale(1.02);
}

/* 个人信息卡片 */
.profile-wrapper {
  position: relative;
  z-index: 1;
  width: 100%;
  max-width: 600px;
}

.profile-card {
  padding: 48px 24px 24px;
  margin-bottom: 24px;
}

.avatar-ring {
  width: 120px;
  height: 120px;
  border-radius: 50%;
  background: linear-gradient(45deg, #4a90e2, #5aa1ff);
  padding: 6px;
  margin: 0 auto 20px;
  box-shadow: 0 8px 24px rgba(74, 144, 226, 0.3);
  transition: transform 0.3s ease;
  cursor: pointer;
}

.avatar-ring:hover {
  transform: scale(1.05);
}

.avatar {
  width: 100%;
  height: 100%;
  border-radius: 50%;
  border: 3px solid white;
}

.info-grid {
  display: grid;
  grid-template-columns: 1fr;
  gap: 16px;
}

.info-item {
  display: flex;
  align-items: center;
  padding: 12px;
  background: rgba(255, 255, 255, 0.6);
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  transition: background 0.2s ease;
}

.info-item:hover {
  background: rgba(74, 144, 226, 0.1);
}

.info-label {
  margin-left: 12px;
  font-size: 16px;
  color: #333;
  font-weight: 500;
}

/* 数据统计卡片 */
.stats-card {
  display: flex;
  justify-content: space-evenly; /* 均匀分布 */
  padding: 24px;
  border-radius: 18px;
  margin-bottom: 24px;
  background: rgba(255, 255, 255, 0.9);
  box-shadow: 0 8px 24px rgba(74, 144, 226, 0.1);
}

.stat-item {
  text-align: center;
  flex: 1;
}

.stat-value {
  display: block;
  font-size: 24px;
  font-weight: 700;
  color: #4a90e2;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 12px;
  color: #666;
  text-transform: uppercase;
  letter-spacing: 1px;
}

.divider {
  width: 1px;
  height: 40px;
  background: rgba(74, 144, 226, 0.1); /* 更深的颜色 */
  margin: 10px 16px; /* 增加间距 */
}

/* 操作按钮 */
.action-buttons {
  display: flex;
  justify-content: center;
  width: 100%;
}

.logout-button {
  border: none;
  border-radius: 12px;
  padding: 16px;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  max-width: 300px;
  background: linear-gradient(45deg, #ff6b6b, #ff8787);
  box-shadow: 0 4px 12px rgba(255, 107, 107, 0.3);
  transition: transform 0.3s ease, box-shadow 0.3s ease;
}

.logout-button:hover {
  transform: scale(1.05);
  box-shadow: 0 6px 16px rgba(255, 107, 107, 0.4);
}

.logout-button text {
  margin-left: 8px;
  font-size: 16px;
  font-weight: 500;
}

/* 加载动画 */
.loading {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  display: flex;
  flex-direction: column;
  align-items: center;
  z-index: 1000;
  color: #666;
}

.spinner {
  width: 24px;
  height: 24px;
  border: 3px solid rgba(74, 144, 226, 0.3);
  border-radius: 50%;
  border-top-color: #4a90e2;
  animation: spin 1s linear infinite;
  margin-bottom: 8px;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

/* 动画效果 */
@keyframes cardEnter {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.profile-card,
.stats-card {
  animation: cardEnter 0.6s cubic-bezier(0.23, 1, 0.32, 1);
}
</style>